package com.dal.module.payment;

import com.dal.constant.PaymentConstant;
import com.dal.db.bean.RechargeOrder;
import com.dal.db.cache.RechargeOrderCache;
import com.dal.manager.PaymentManager;
import com.dal.module.BaseController;
import com.google.common.collect.Maps;
import com.sojoys.artifact.annotation.IController;
import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.tools.security.md.ToolMD;
import com.sojoys.artifact.tools.security.md.ToolMD5;

import java.util.Map;

/**
 * Created by fxf on 2018-2-8.
 */
@IController("/payment")
@SuppressWarnings({"rawtypes", "unchecked"})
public class PaymentController extends BaseController {

    public void PaymentNotice(){
        //游戏区服标识
        String sid = getPara(PaymentConstant.SID);
        //黑桃用户 ID
        Integer uid = getParaToInt(PaymentConstant.UID);
        //黑桃支付订单号(唯一)
        String orderNo = getPara(PaymentConstant.ORDERNO);
        //充值金额
        Integer amount = Integer.valueOf(getPara(PaymentConstant.AMOUNT));
        //状态（1 成功， 2 失败）
        Integer status = getParaToInt(PaymentConstant.STATUS);
        //扩展信息
        String extInfo = getPara(PaymentConstant.EXTINFO);
        //签名时间戳
        String ht_nonce = getPara(PaymentConstant.HTNONCE);
        //签名
        String htToken = getPara(PaymentConstant.HTTOKEN);

        if (sid == null || uid == null || orderNo == null || amount == null
                || status == null || extInfo == null || ht_nonce == null || htToken == null){
            return;
        }


        //校验签名
        String token = sid + uid + orderNo + amount + extInfo + ht_nonce + PaymentConstant.SECRET;
        if (!htToken.equals(ToolMD5.encodeMD5Hex(token))){
            renderErr("token is wrong");
            return ;
        }

        //校验订单
        RechargeOrder order =  RechargeOrderCache.me().getById(extInfo);
        if (order == null){
            renderErr("order not find");
            return;
        }

        if (order.getState() == PaymentConstant.ORDER_STATE_ALREADY_PAID){
            renderErr("order already payment");
            return;
        }

        order.setUid(uid);
        order.setOrderno(orderNo);
        order.setAmount(amount);
        order.setAllParam(getParaMap().toString());
        order.update();

        try {
            PaymentManager.paymentNotice(order);
        } catch (AbstractLogicModelException e) {

            e.printStackTrace();
        }

        renderSuccess("success","success");
    }

    private void renderErr(String errMsg){
        Map map = Maps.newHashMap();
        map.put("errno",1);
        map.put("errmsg",errMsg);
        renderSuccess(map,"fail");
    }
}